<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>02.React生命周期(旧)</title>
    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>
</head>

<body>
    <div id="app"></div>
    <script type="text/babel">
        class Counter extends React.Component{
            // 组件挂载流程
            // 构造器：组件创建时调用
            constructor(){
                console.log('Constructure')
                super()
                this.state = {
                    count: 1
                }
            }

            // 生命周期钩子函数，从 props 中获取派生的状态
            // render 之前调用，用于接收 props 用于修改 state
            static getDerivedStateFromProps(props, state){
                console.log('getDerivedStateFromProps');
                // 返回对象用以修改 state
                return {
                    name: props.name
                }
            }

            // 生命周期钩子函数，获取先前的状态，并传递给 componentDidUpdate()
            getSnapshotBeforeUpdate(){
                console.log('getSnapshotBeforeUpdate');
                return 'snapshot_Value'
            }

            // 生命周期钩子函数，组件完成更新后调用，接收三个参数: prevProps, preState, snapshotValue
            componentDidUpdate(prevProps, preState, snapshotValue){
                console.log('componentDidUpdate');
                console.log('preProps:',prevProps);
                console.log('preState:',preState);
            }

           
            // 生命周期钩子函数： 组件靠此函数渲染
            render(){
                console.log('render')
                return (
                    <div>
                        <h1>当前点赞数： {this.state.count}</h1>
                        <button onClick={this.add}>赞 + 1</button>
                        <button onClick={this.removeComponent}>别点赞了！</button>
                        <button onClick={this.refreshComponent}>强制刷新</button>
                    </div>
                )
            }

            add = ()=> {
                const {count} = this.state
                this.setState({
                    count: count + 1
                })
            }

            removeComponent = () => {
                ReactDOM.unmountComponentAtNode(document.querySelector('#app'))
            }

            // 刷新组件
            refreshComponent = () => {
                //  强制更新组件，不会调用 shouldComponentUpdate()
                this.forceUpdate()
            }
        }

        ReactDOM.render(<Counter name='counter'/>, document.querySelector('#app'))
    </script>
</body>

</html>
